//引入exress模块
const express = require('express');
//引入连接池模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();


//用户注册并且验证唯一性接口  
r.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let uname = req.body.uname;
  let upwd = req.body.upwd;
  //以uname为条件进行查找操作，以保证用户名的唯一性
  let sql = 'select count(uid) as count from userInf where uname=?';
  pool.query(sql, [uname], (err, result) => {
    if (err) throw err;
    let count = result[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'insert userInf (uname,upwd) values(?,md5(?))';
      pool.query(sql, [uname, upwd], (err, result) => {
        if (err) throw err;
        res.send({
          message: 'ok',
          code: 200
        });
      })
    } else {
      res.send({
        message: '用户名已存在',
        code: 201
      });
    }
  });
});

// //获取验证码
// r.get('/code',(req,res)=>{
//   pool.query((err,result)=>{
//       if (err) throw err;
//       const tencentcloud = require("tencentcloud-sdk-nodejs");
//       const SmsClient = tencentcloud.sms.v20210111.Client;
//       const clientConfig = {
//         credential: {
//           secretId: "AKIDsZ0A3f04qMcbJkunQnthEUTBcmfHcgTz",
//           secretKey: "GFxNWO0MQDixkHYdU4NO9dpkOkpc8ON5",
//         },
//         region: "ap-nanjing",
//         profile: {
//           httpProfile: {
//             endpoint: "sms.tencentcloudapi.com",
//           },
//         },
//       };
//       const client = new SmsClient(clientConfig);
//       // 定义函数保存随机四位数的验证码
//       function random(len){
//         var charts = '0123456789';
//         var checkCode = '';
//         for(var i=0;i<len;i++){
//           checkCode +=charts.charAt(Math.floor(Math.random()*charts.length));
//         }
//         return checkCode;
//       }
//       var ranDom = random(4);
//       const params = {
//         "PhoneNumberSet": [`+86${_tel}`], //从前端页面获取到的手机号
//         "SmsSdkAppId": "1400557736",
//         "SignName": "XCCZLL",
//         "TemplateId": "1073409",
//         "TemplateParamSet": [ranDom]
//       };
//       client.SendSms(params).then(
//         (data) => {
//           console.log(data);
//         },
//         (err) => {
//           console.error("error", err);
//         }
//       );
//       res.send(ranDom)
//    })
// })


//用户获取验证码登录
r.post('/login', (req, res) => {
  var _tel = req.body.tel;
  var sql = "select * from userInf where tel=?";
  pool.query(sql, [_tel], (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      const tencentcloud = require("tencentcloud-sdk-nodejs");
      const SmsClient = tencentcloud.sms.v20210111.Client;
      const clientConfig = {
        credential: {
          secretId: "AKIDsZ0A3f04qMcbJkunQnthEUTBcmfHcgTz",
          secretKey: "GFxNWO0MQDixkHYdU4NO9dpkOkpc8ON5",
        },
        region: "ap-nanjing",
        profile: {
          httpProfile: {
            endpoint: "sms.tencentcloudapi.com",
          },
        },
      };
      const client = new SmsClient(clientConfig);
      // 定义函数保存随机四位数的验证码
      function random(len){
        var charts = '0123456789';
        var checkCode = '';
        for(var i=0;i<len;i++){
          checkCode +=charts.charAt(Math.floor(Math.random()*charts.length));
        }
        return checkCode;
      }
      var ranDom = random(4);
      const params = {
        "PhoneNumberSet": [`+86${_tel}`], //从前端页面获取到的手机号
        "SmsSdkAppId": "1400557736",
        "SignName": "XCCZLL",
        "TemplateId": "1073409",
        "TemplateParamSet": [ranDom]
      };
      client.SendSms(params).then(
        (data) => {
          console.log(data);
        },
        (err) => {
          console.error("error", err);
        }
      );
      res.send(ranDom);
    } else {
      res.send("0");
    }
  });
});



// 获取用户表里的数据内容
r.get('/data', (req, res) => {
  let uid = req.query
  //SQL语句以用户表里的所有数据
  let sql = 'select * from userInf where uid=?';
  //执行SQL语句
  pool.query(sql, [uid], (err, results) => {
    if (err) throw err;
    res.send({
      message: 'ok',
      code: 200,
      results: results
    });
  });
});


//导出路由器对象
module.exports = r;